/**
 * 
 */
package fr.toussna.ui;

/**
 * 
 */

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import fr.toussna.entity.Category;
import fr.toussna.service.LocalAccountService;

public class Console implements ActionListener, WindowListener {
	JFrame f;
	JPanel pane;
	JTextField name;
	LocalAccountService local = new LocalAccountService();
	List<Category> list = local.getCategorie();

	public Console() {

		constructFarme();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().contains("Delete")) {
			String iden = e.getActionCommand().replaceAll("[A-Za-z]", "");
			Category category = new Category(new Long(iden.trim()));
			local.deleteCategory(category);
			list = local.getCategorie();
			f.removeAll();
			f.setVisible(false);
			f.dispose();
			f = null;
			constructFarme();
		} else if (e.getActionCommand().equals("Add category :")) {
			local.createCategory(name.getText().trim());
			name.setText("  ");

		}
	}

	public static void main(String[] args) {
		new Console();
	}

	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowClosing(WindowEvent e) {
		System.exit(0);

	}

	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	private void constructFarme() {
		f = new JFrame("WSClient");
		pane = new JPanel();
		if (list != null) {
			for (Category category : list) {
				JLabel label = new JLabel(category.getName());
				JButton b = new JButton("Delete " + category.getId());
				pane.add(label);
				pane.add(b);
				pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

				b.addActionListener(this);

			}
		}
		name = new JTextField("give a name to your category");
		pane.add(name);
		JButton b2 = new JButton("Add category :");
		pane.add(b2);
		b2.addActionListener(this);
		pane.setSize(600, 700);
		f.getContentPane().add(pane, BorderLayout.CENTER);
		f.setSize(600, 750);
		f.setVisible(true);
	}

}
